package com.adk.backend.service.impl;

import com.adk.backend.common.PageResult;
import com.adk.backend.entity.LxBookingFlight;
import com.adk.backend.entity.LxBookingL;
import com.adk.backend.mapper.BookingFlightMapper;
import com.adk.backend.mapper.BookingMapper;
import com.adk.backend.service.BookingService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订舱服务实现类
 */
@Slf4j
@Service
public class BookingServiceImpl extends ServiceImpl<BookingMapper, LxBookingL> implements BookingService {
    
    @Autowired
    private BookingMapper bookingMapper;
    
    @Autowired
    private BookingFlightMapper bookingFlightMapper;
    
    @Override
    public PageResult<Map<String, Object>> getBookingList(Map<String, Object> params) {
        Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) params.getOrDefault("pageSize", 20);
        
        // 计算偏移量
        Integer offset = (pageNum - 1) * pageSize;
        params.put("offset", offset);
        params.put("pageSize", pageSize);
        
        // 查询总数
        Long total = bookingMapper.countBookingList(params);
        
        // 查询列表
        List<Map<String, Object>> list = bookingMapper.selectBookingListWithInfo(params);
        
        PageResult<Map<String, Object>> result = new PageResult<>();
        result.setList(list);
        result.setTotal(total);
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);
        result.setTotalPages((int) Math.ceil((double) total / pageSize));
        
        return result;
    }
    
    @Override
    public LxBookingL getBookingById(Long id) {
        return bookingMapper.selectById(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LxBookingL createBooking(LxBookingL booking, Integer userId) {
        int currentTime = (int) (System.currentTimeMillis() / 1000);
        if (booking.getAddTime() == null) {
            booking.setAddTime(currentTime);
        }
        // 与PHP逻辑一致：设置add_uid
        if (userId != null) {
            booking.setAddUid(userId);
        }
        // 注意：planDate, eta, etd字段在数据库中是时间戳（Integer），前端传入的应该是时间戳
        // 如果需要支持字符串日期格式，应在Controller层转换
        bookingMapper.insert(booking);
        return booking;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBooking(LxBookingL booking, Integer userId) {
        // 与PHP逻辑一致：更新时设置add_time和add_uid
        int currentTime = (int) (System.currentTimeMillis() / 1000);
        booking.setAddTime(currentTime);
        if (userId != null) {
            booking.setAddUid(userId);
        }
        // 注意：planDate, eta, etd字段在数据库中是时间戳（Integer），前端传入的应该是时间戳
        // 如果需要支持字符串日期格式，应在Controller层转换
        return bookingMapper.updateById(booking) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBooking(Long id, Integer userId) {
        // 与PHP逻辑一致：直接删除（delete from lx_booking_l where id=xxx）
        return bookingMapper.deleteById(id) > 0;
    }
    
    @Override
    public List<Map<String, Object>> getFlightList(Map<String, Object> params) {
        QueryWrapper<LxBookingFlight> wrapper = new QueryWrapper<>();
        if (params.get("orderId") != null) {
            wrapper.eq("order_id", params.get("orderId"));
        }
        if (params.get("slId") != null) {
            wrapper.eq("sl_id", params.get("slId"));
        }
        if (params.get("type") != null) {
            wrapper.eq("type", params.get("type"));
        }
        wrapper.orderByDesc("flight_date_int");
        
        List<LxBookingFlight> flights = bookingFlightMapper.selectList(wrapper);
        List<Map<String, Object>> result = new java.util.ArrayList<>();
        for (LxBookingFlight flight : flights) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", flight.getId());
            map.put("type", flight.getType());
            map.put("orderId", flight.getOrderId());
            map.put("flightNo", flight.getFlightNo());
            map.put("flightDate", flight.getFlightDate());
            map.put("flightDateInt", flight.getFlightDateInt());
            map.put("flightNo2", flight.getFlightNo2());
            map.put("flightDate2", flight.getFlightDate2());
            map.put("flightDateInt2", flight.getFlightDateInt2());
            map.put("flightType", flight.getFlightType());
            map.put("slId", flight.getSlId());
            result.add(map);
        }
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addFlight(LxBookingFlight flight) {
        if (flight.getAddTime() == null) {
            flight.setAddTime((int) (System.currentTimeMillis() / 1000));
        }
        if (flight.getFlightDate() != null && flight.getFlightDateInt() == null) {
            try {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                java.util.Date date = sdf.parse(flight.getFlightDate());
                flight.setFlightDateInt((int) (date.getTime() / 1000));
            } catch (Exception e) {
                log.error("日期解析失败", e);
            }
        }
        if (flight.getFlightDate2() != null && flight.getFlightDateInt2() == null) {
            try {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                java.util.Date date = sdf.parse(flight.getFlightDate2());
                flight.setFlightDateInt2((int) (date.getTime() / 1000));
            } catch (Exception e) {
                log.error("日期解析失败", e);
            }
        }
        return bookingFlightMapper.insert(flight) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateFlight(LxBookingFlight flight) {
        if (flight.getUpdateTime() == null) {
            flight.setUpdateTime((int) (System.currentTimeMillis() / 1000));
        }
        if (flight.getFlightDate() != null && flight.getFlightDateInt() == null) {
            try {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                java.util.Date date = sdf.parse(flight.getFlightDate());
                flight.setFlightDateInt((int) (date.getTime() / 1000));
            } catch (Exception e) {
                log.error("日期解析失败", e);
            }
        }
        if (flight.getFlightDate2() != null && flight.getFlightDateInt2() == null) {
            try {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                java.util.Date date = sdf.parse(flight.getFlightDate2());
                flight.setFlightDateInt2((int) (date.getTime() / 1000));
            } catch (Exception e) {
                log.error("日期解析失败", e);
            }
        }
        return bookingFlightMapper.updateById(flight) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteFlight(Long id) {
        return bookingFlightMapper.deleteById(id) > 0;
    }
    
    @Override
    public List<Map<String, Object>> getFlightCompanies() {
        // 查询航班公司列表，type=2表示航司，is_del=0表示未删除
        return bookingMapper.selectFlightCompanies();
    }
}

